<template>
  <a-spin :spinning="loading">
    <a-form v-bind="formItemLayout">
      <a-row>
        <a-col :span="12">
          <a-form-item label="环境名称" v-bind="validateInfos.evnName">
            <a-input v-model:value="formData.evnName" placeholder="请输入环境名称" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="阶段" v-bind="validateInfos.testStageId">
	          <j-dict-select-tag v-model:value="formData.testStageId" dictCode="tm_test_stage,test_stage_name,id" placeholder="请选择阶段" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="url" v-bind="validateInfos.url">
            <a-input v-model:value="formData.url" placeholder="请输入url" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="描述" v-bind="validateInfos.description">
	          <a-textarea v-model:value="formData.description" :rows="4" placeholder="请输入描述" :disabled="disabled"/>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

		<!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated>
      <a-tab-pane tab="环境参数" key="tmTestEnvParam" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="tmTestEnvParamTableRef"
          :loading="tmTestEnvParamTable.loading"
          :columns="tmTestEnvParamTable.columns"
          :dataSource="tmTestEnvParamTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { queryTmTestEnvParamListByMainId, queryDataById, saveOrUpdate } from '../TestEnv.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {tmTestEnvParamColumns} from '../TestEnv.data';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { Form } from 'ant-design-vue';
  const useForm = Form.useForm;

  export default defineComponent({
    name: "TestEnvForm",
    components:{
      JDictSelectTag,
      JVxeTable,
    },
    props:{
      formDisabled:{
        type: Boolean,
        default: false
      },
      formData: { type: Object, default: ()=>{} },
      formBpm: { type: Boolean, default: true }
    },
    emits:['success'],
    setup(props, {emit}) {
      const loading = ref(false);
      const tmTestEnvParamTableRef = ref();
      const tmTestEnvParamTable = reactive<Record<string, any>>({
        loading: false,
        columns: tmTestEnvParamColumns,
        dataSource: []
      });
      const activeKey = ref('tmTestEnvParam');
      const formData = reactive<Record<string, any>>({
        id: '',
        evnName: '',   
        testStageId: '',   
        url: '',   
        description: '',   
      });

      //表单验证
      const validatorRules = reactive({
        evnName: [{ required: true, message: '请输入环境名称!'},],
        testStageId: [{ required: true, message: '请输入阶段!'},],
        url: [{ required: true, message: '请输入url!'},],
      });
      const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: true});
      const dbData = {};
      const formItemLayout = {
        labelCol: {xs: {span: 24}, sm: {span: 5}},
        wrapperCol: {xs: {span: 24}, sm: {span: 16}},
      };

      // 表单禁用
      const disabled = computed(()=>{
        if(props.formBpm === true){
          if(props.formData.disabled === false){
            return false;
          }else{
            return true;
          }
        }
        return props.formDisabled;
      });

      

      function add() {
        resetFields();
        tmTestEnvParamTable.dataSource = [];
      }

      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const tmTestEnvParamDataList = await queryTmTestEnvParamListByMainId(row['id']);
        tmTestEnvParamTable.dataSource = [...tmTestEnvParamDataList];
      }

      async function queryMainData(id) {
        const row = await queryDataById(id);
        Object.keys(row).map(k => {
          formData[k] = row[k];
        });
      }

      const {getSubFormAndTableData, transformData} = useValidateAntFormAndTable(activeKey, {
        'tmTestEnvParam': tmTestEnvParamTableRef,
      });

      async function getFormData() {
        await validate();
        return transformData(toRaw(formData))
      }

      async function submitForm() {
        const mainData = await getFormData();
        const subData = await getSubFormAndTableData();
        const values = Object.assign({}, dbData, mainData, subData);
        console.log('表单提交数据', values)
        const isUpdate = values.id ? true : false
        await saveOrUpdate(values, isUpdate);
        //关闭弹窗
        emit('success');
      }
      
      function setFieldsValue(values) {
        if(values){
          Object.keys(values).map(k=>{
            formData[k] = values[k];
          });
        }
      }

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }


      return {
        tmTestEnvParamTableRef,
        tmTestEnvParamTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit
      }
    }
  });
</script>